package com.lms.demo.autoconfigure.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.lms.demo.autoconfigure.ObjectStorage;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-12-25 15:37
 * @Description:
 */
public class OSSTemplate implements ObjectStorage {

    private final OSS ossClient;

    public OSSTemplate(OSSProperties ossProperties) {
        this(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getSecretAccessKey());
    }

    public OSSTemplate(String endpoint, String accessKeyId, String secretAccessKey) {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey);
    }


    @Override
    public void uploadObjectByInputStream(String buckName, String objectName, InputStream inputStream) {
        PutObjectResult putObjectResult = ossClient.putObject(buckName, objectName, inputStream);
    }

    @Override
    public void uploadObjectByMultipartFile(String buckName, String objectName, MultipartFile multipartFile) throws IOException {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            uploadObjectByInputStream(buckName, objectName, inputStream);
        }
    }

    @Override
    public void uploadObjectByBytes(String buckName, String objectName, byte[] content) throws IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(content)) {
            uploadObjectByInputStream(buckName, objectName, bais);
        }
    }

    @Override
    public InputStream downloadByObjectName(String buckName, String objectName) {
        OSSObject object = ossClient.getObject(buckName, objectName);
        return object.getObjectContent();
    }
}
